

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/home_controller.dart';
import '../../../utils/keepAliveWrapper.dart'; // 缓存切换的页面，防止页面切换时状态丢失
import '../../../utils/screenAdapter.dart'; // 屏幕适配插件
import 'package:flutter_swiper_view/flutter_swiper_view.dart'; // 轮播图插件
import '../../../utils/myFonts.dart';
import '../../../service/HttpsClient.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; // 瀑布流插件

class HomeView extends GetView<HomeController> {
  const HomeView({super.key});
  // 顶部自定义导航区域
  Widget _appBar() {
    return Obx(
      () => Positioned(
        left: 0,
        top: 0,
        right: 0,
        child: AppBar(
          backgroundColor: Colors.transparent, // 导航栏背景颜色透明
          // scrolledUnderElevation: 0, // 向下滑动时背景阴影为0
          // elevation: 0, // 阴影高度为0
          leading: controller.flag.value
              ? Text("")
              : Icon(
                  MyFonts.xiaomi,
                  color: Colors.orange,
                  size: ScreenAdapter.fontSize(60),
                ),
          title: InkWell(
            child: AnimatedContainer(
              // 搜索框动画效果
              transform: controller.flag.value
                  ? Matrix4.translationValues(-ScreenAdapter.width(120), 0, 0)
                  : Matrix4.translationValues(0, 0, 0),
              duration: 200.milliseconds, // 动画时长
              width: controller.flag.value
                  ? ScreenAdapter.width(880)
                  : ScreenAdapter.width(600),
              height: ScreenAdapter.height(96),
              decoration: BoxDecoration(
                color: Color.fromARGB(187, 244, 240, 240),
                borderRadius: BorderRadius.circular(ScreenAdapter.radius(50)),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      IconButton(
                        onPressed: null,
                        icon: Icon(
                          Icons.search,
                          size: ScreenAdapter.fontSize(46),
                        ),
                        color: Color.fromARGB(187, 185, 185, 185),
                      ),
                      Text(
                        // controller.searchwords, // 搜索框内容
                        "请输入搜索内容",
                        style: TextStyle(
                          fontSize: ScreenAdapter.fontSize(30),
                          color: Color.fromARGB(187, 185, 185, 185),
                        ),
                      ),
                    ],
                  ),
                  IconButton(
                    onPressed: () {},
                    icon: Icon(MyFonts.saoma, size: ScreenAdapter.fontSize(46)),
                    color: Color.fromARGB(187, 185, 185, 185),
                  ),
                ],
              ),
            ),
            onTap: () {
              Get.toNamed("/search");
            },
          ),
          actions: [
            IconButton(
              onPressed: () {},
              icon: controller.flag.value
                  ? Text("")
                  : Icon(Icons.qr_code, size: ScreenAdapter.fontSize(60)),
              color: Colors.orange,
            ),
            IconButton(
              onPressed: () {},
              icon: Icon(Icons.message, size: ScreenAdapter.fontSize(60)),
              color: Colors.orange,
            ),
          ], // 操作按钮
        ),
      ),
    );
  }

  // 轮播图区域
  // 自定义轮播图组件
  Widget _swiper({
    int heigt = 700,
    int width = 1080,
    BoxFit fit = BoxFit.cover,
  }) {
    return SizedBox(
      height: ScreenAdapter.height(heigt),
      width: ScreenAdapter.width(width),
      child: Obx(
        () => Swiper(
          // Swiper组件不能直接放在ListView中，需要在外面包裹SizedBox或者Container组件
          itemBuilder: (context, index) {
            String pic = HttpsClient.getImgUrl(
              controller.swiperList[index].pic!,
            );
            // print("pic$pic");
            return Image.network(pic, fit: fit);
          },
          itemCount: controller.swiperList.length, // 轮播图数量
          pagination: const SwiperPagination(
            builder: SwiperPagination.rect,
          ), // 分页指示器
          // control: const SwiperControl(), // 左右两边切换箭头
          autoplay: true, // 自动轮播
          autoplayDelay: 1500, // 自动轮播时间间隔
          loop: true, // 是否循环播放
          // duration: 2000, // 切换动画时间
        ),
      ),
    );
  }

  // banner区域
  Widget _banner() {
    return SizedBox(
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(80),
      child: Image.asset("assets/images/xiaomiBanner.png", fit: BoxFit.cover),
    );
  }

  // 轮播分类网格布局
  Widget _swiperCategory() {
    return Container(
      // Swiper外面必须包裹宽高容器，否则会报错
      color: Colors.white,
      width: ScreenAdapter.width(1080),
      height: ScreenAdapter.height(600),
      child: Obx(
        () => Swiper(
          itemCount: controller.categoryList.length ~/ 10, // 轮播数量（向上取整)
          itemBuilder: (context, index1) => GridView.builder(
            // scrollDirection: Axis.horizontal,  滚动方向，默认是垂直方向
            physics: NeverScrollableScrollPhysics(), // 禁止GridView上下滑动
            itemCount: 10, // 网格布局数量
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              // 控制子控件的排列布局
              crossAxisSpacing: ScreenAdapter.width(20), // 侧轴方向上子控件间距--水平方向
              mainAxisSpacing: ScreenAdapter.height(20), // 主轴方向上子控件间距(两行之间的间距)
              crossAxisCount: 5, // 每行显示5个
            ),
            itemBuilder: (context, index2) {
              String pic = HttpsClient.getImgUrl(
                controller.categoryList[index1 * 10 + index2].pic!,
              );
              return Column(
                children: [
                  Container(
                    alignment: Alignment.center,
                    width: ScreenAdapter.height(140),
                    height: ScreenAdapter.height(140),
                    child: Image.network(
                      pic, // 替换字符串中的反斜杠为斜杠
                      fit: BoxFit.fitHeight,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: ScreenAdapter.height(20)),
                    child: Text(
                      "${controller.categoryList[index1 * 10 + index2].title}",
                      style: TextStyle(fontSize: ScreenAdapter.fontSize(28)),
                    ),
                  ),
                ],
              );
            },
          ),
          pagination: SwiperPagination(
            // margin: const EdgeInsets.all(0.0),
            builder: SwiperCustomPagination(
              // 自定义分页器样式
              builder: (BuildContext context, SwiperPluginConfig config) {
                return ConstrainedBox(
                  constraints: BoxConstraints.expand(
                    height: ScreenAdapter.height(40),
                  ),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Align(
                          alignment: Alignment.center,
                          child: RectSwiperPaginationBuilder(
                            size: Size(ScreenAdapter.width(60), 3.0),
                            activeSize: Size(ScreenAdapter.width(60), 3.0),
                            color: Colors.black12,
                            activeColor: Colors.black54,
                          ).build(context, config),
                        ),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  // 圆形广告背景图片
  Widget _bannerBg() {
    return Container(
      height: ScreenAdapter.height(470),
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.fromLTRB(
          ScreenAdapter.width(30),
          ScreenAdapter.height(20),
          ScreenAdapter.width(30),
          ScreenAdapter.height(30),
        ),
        child: Container(
          height: ScreenAdapter.height(420),
          decoration: BoxDecoration(
            // color: Colors.pink,
            image: DecorationImage(
              image: AssetImage("assets/images/xiaomiBanner2.png"),
              fit: BoxFit.cover,
            ),
            borderRadius: BorderRadius.circular(ScreenAdapter.radius(20)),
          ),
        ),
      ),
    );
  }

  // 热销臻选标题
  Widget _bestSelling({required String leftTxt, required String rightTxt}) {
    return Container(
      padding: EdgeInsets.fromLTRB(
        ScreenAdapter.width(30),
        0,
        ScreenAdapter.width(30),
        0,
      ),
      color: Colors.white,
      height: ScreenAdapter.height(90),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Text(
            "$leftTxt",
            style: TextStyle(
              fontSize: ScreenAdapter.fontSize(46),
              fontWeight: FontWeight.bold,
            ),
          ),
          Text(
            "$rightTxt",
            style: TextStyle(fontSize: ScreenAdapter.fontSize(38)),
          ),
        ],
      ),
    );
  }

  // 热销甄选图片展示区
  Widget _bestSellingImage() {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: EdgeInsets.fromLTRB(
          ScreenAdapter.width(30),
          ScreenAdapter.height(20),
          ScreenAdapter.width(30),
          ScreenAdapter.height(30),
        ),
        child: Row(
          spacing: ScreenAdapter.width(30), // 左右间距
          children: [
            Expanded(flex: 1, child: _swiper(heigt: 800)),
            // SizedBox(width: ScreenAdapter.width(30)),
            Expanded(
              flex: 1,
              child: SizedBox(
                height: ScreenAdapter.height(800),
                // color: Colors.green,
                child: Obx(
                  () => Column(
                    spacing: ScreenAdapter.height(20),
                    children: controller.plistList.map((val) {
                      var picUrl = HttpsClient.getImgUrl(val.pic!);
                      return Expanded(
                        flex: 1,
                        child: Container(
                          color: const Color.fromARGB(31, 160, 159, 159),
                          child: Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: Column(
                                  mainAxisAlignment:
                                      MainAxisAlignment.center, // 垂直居中
                                  children: [
                                    Container(
                                      padding: EdgeInsets.only(
                                        left: ScreenAdapter.width(30),
                                      ),
                                      width: double.infinity, // 宽度充满外面的容器
                                      child: Text(
                                        "${val.title}",
                                        textAlign: TextAlign.left,
                                        style: TextStyle(
                                          fontWeight: FontWeight.bold,
                                          fontSize: ScreenAdapter.fontSize(30),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      padding: EdgeInsets.only(
                                        left: ScreenAdapter.width(30),
                                      ),
                                      width: double
                                          .infinity, // 由于在Column中的Text组件宽度是自适应外面Column的宽度，无法让Text组件向左对齐，
                                      // 所以需要将Text组件放在一个Container中，并设置Container的宽度为double.infinity，这样Text组件就可以向左对齐了
                                      child: Text(
                                        val.subTitle ??
                                            "", // 如果subTitle为null，则显示空字符串
                                        textAlign: TextAlign.left,
                                        style: TextStyle(
                                          fontSize: ScreenAdapter.fontSize(26),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      width: double.infinity,
                                      padding: EdgeInsets.only(
                                        left: ScreenAdapter.width(30),
                                      ),
                                      child: Text(
                                        "￥${val.price}",
                                        textAlign: TextAlign.left,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Expanded(
                                flex: 2,
                                child: Align(
                                  alignment: Alignment.centerRight,
                                  child: SizedBox(
                                    height: ScreenAdapter.height(220),
                                    child: Image.network(
                                      picUrl,
                                      fit: BoxFit.fitHeight,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 热门商品瀑布流
  Widget _hotGoods() {
    return Column(
      children: [
        Container(
          padding: EdgeInsets.all(ScreenAdapter.width(26)),
          color: const Color.fromRGBO(246, 246, 246, 1),
          child: Obx(
            () => MasonryGridView.count(
              crossAxisCount: 2, // 显示列数
              mainAxisSpacing: ScreenAdapter.width(20), // 垂直方向间距
              crossAxisSpacing: ScreenAdapter.width(20), // 水平方向间距
              shrinkWrap: true, // 必须设置，让元素宽度自适应
              itemCount: controller.bestPlist.length, // 商品数量必传
              physics:
                  NeverScrollableScrollPhysics(), // 在ListView中禁止MasonryGridView上下滑动否则会导致页面卡顿
              itemBuilder: (BuildContext context, int index) {
                // double height = 900 + 300 * Random().nextDouble(); // 随机高度
                return GestureDetector(
                  onTap: () {
                    Get.toNamed("/goods-details", arguments:{"goodsId" : controller.bestPlist[index].sId});
                  },
                  child: Container(
                    // height: ScreenAdapter.height(
                    //   height,
                    // ), // 瀑布流布局正常是根据返回的数据内容来动态展示内容高度，这里为了测试效果，所以直接写死高度
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(
                        ScreenAdapter.radius(20),
                      ),
                    ),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.all(ScreenAdapter.width(20)),
                          child: Image.network(
                            HttpsClient.getImgUrl(
                              controller.bestPlist[index].pic!,
                            ),
                            fit: BoxFit.cover,
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(
                            left: ScreenAdapter.width(20),
                            top: ScreenAdapter.height(30),
                          ),
                          width: double.infinity,
                          child: Text(
                            "${controller.bestPlist[index].title}",
                            textAlign: TextAlign.left,
                            style: TextStyle(
                              fontSize: ScreenAdapter.fontSize(42),
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(
                            left: ScreenAdapter.width(20),
                          ),
                          width: double.infinity,
                          child: Text(
                            "${controller.bestPlist[index].subTitle}",
                            style: TextStyle(
                              fontSize: ScreenAdapter.fontSize(32),
                            ),
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(
                            left: ScreenAdapter.width(20),
                            bottom: ScreenAdapter.height(30),
                          ),
                          width: double.infinity,
                          child: Text(
                            "￥${controller.bestPlist[index].price}",
                            style: TextStyle(
                              fontSize: ScreenAdapter.fontSize(32),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  }

  // 页面主体
  Widget _pageBody() {
    return Positioned(
      top: -ScreenAdapter.width(46),
      left: 0,
      right: 0,
      bottom: 0,
      child: ListView(
        controller: controller.scrollController, // 滚动控制器
        children: [
          _swiper(), // 轮播图
          _banner(), // 广告
          _swiperCategory(), // 分类
          _bannerBg(), // 圆形banner背景图片
          _bestSelling(leftTxt: "热销甄选", rightTxt: "更多手机推荐 >"), //   热销甄选
          _bestSellingImage(), // 热销甄选图片
          _bestSelling(leftTxt: "省心优惠", rightTxt: "全部优惠"), //   省心优惠标题
          _hotGoods(), // 热门商品
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return KeepAliveWrapper(
      child: Scaffold(
        body: Stack(
          // Stack组件可以叠加多个组件，后面的组件会覆盖前面的组件
          children: <Widget>[
            _pageBody(),
            _appBar(), // 顶部导航和状态栏层级比页面主体层级高，所以放在后面
          ],
        ),
      ),
    ); // 缓存页面
  }
}
